const express = require("express");
const router = express.Router();
const { db, knex } = require("../db.js");

/**
 * 将对象中指定键的JSON字符串值转换为仅包含value属性的数组
 * @param {Object} item - 包含目标JSON字符串的对象（如数据库查询结果项）
 * @param {string} key - 需要解析的JSON字符串对应的键名（如"technolog"或"features"）
 * @returns {Array} 解析后的数组，每个元素为原JSON数组中对象的value属性值
 */
function JsonToArray(item, key) {
  return JSON.parse(item[key]).map((i) => {
    return i.value;
  });
}

router.get("/config", async (req, res) => {
  try {
    const config = await db("ba_config")
      .where("id", ">", 13)
      .select("name", "value");
    if (config.length === 0) {
      return res.status(404).json({ error: "Configuration not found" });
    }
    // 格式化配置数据
    // 将每个配置项转换为 { name: value } 的形式 直接返回总体object
    // 例如：{ "siteName": "My Site", "version": "1.0" }

    const formattedConfig = config.reduce((acc, item) => {
      acc[item.name] = item.value;
      return acc;
    }, {});
    // 设置缓存
    res.setHeader("Cache-Control", "public, max-age=3600"); // 缓存1小时
    res.status(200).json(formattedConfig);
  } catch (error) {
    console.error("Error fetching configuration:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/typewriter-texts", async (req, res) => {
  try {
    const a = await db("ba_typewritertexts")
      .orderBy("id", "asc")
      .select("name");
    const count = await db("ba_typewritertexts").count("* as total");
    let data = a.map((item) => item.name);
    res.status(200).json({ data, total: count[0].total });
  } catch (error) {
    console.error("Error fetching typewriter texts:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/timelines", async (req, res) => {
  try {
    let timelines = await db("ba_timeline").orderBy("year", "desc").select();
    const count = await db("ba_timeline").count("* as total");
    timelines = timelines.map((item) => {
      console.log(JSON.parse(item.technolog).map((i) => i.value));
      item.technologies = JsonToArray(item, "technolog");
      item.date = item.data;
      item.skills = JSON.parse(item.skills).map((i) => {
        return { name: i.key, level: i.value };
      });
      return item;
    });

    res.status(200).json({ data: timelines, total: count[0].total });
  } catch (error) {
    console.error("Error fetching timelines:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/projects", async (req, res) => {
  const limit = Number(req.query.limit) || 100; // 默认每页100条
  const page = req.query.page || 1; // 默认页码为1
  console.log("Fetching projects with limit:", limit, "and page:", page);

  if (!limit || isNaN(limit) || limit <= 0) {
    return res.status(400).json({ error: "Invalid limit parameter" });
  }
  const offset = (page - 1) * limit;
  // opt0=HTML,opt1=CSS,opt2=JavaScript,opt3=React,
  // opt4=Vue,opt5=Nodejs,opt6=Java,opt7=Python,opt8=php,
  // opt9=pinia,opt10=vite,opt11=NestJS,opt12=TypeScript,
  // opt13=OBS,opt14=electron,opt15=JQ,opt16=Express,
  // opt17=SASS/LESS,opt18=Webpack
  const box = {
    opt0: "HTML",
    opt1: "CSS",
    opt2: "JavaScript",
    opt3: "React",
    opt4: "Vue",
    opt5: "Nodejs",
    opt6: "Java",
    opt7: "Python",
    opt8: "php",
    opt9: "pinia",
    opt10: "vite",
    opt11: "NestJS",
    opt12: "TypeScript",
    opt13: "OBS",
    opt14: "electron",
    opt15: "JQ",
    opt16: "Express",
    opt17: "SASS/LESS",
    opt18: "Webpack",
  };

  try {
    let projects = await db("ba_project")
      .limit(limit)
      .offset(offset)
      .orderBy("weigh", "desc")
      .select();
    const count = await db("ba_project").count("* as total");
    projects = projects.map((item) => {
      item.tags = item.checkbox.split(",").map((i) => {
        return box[i] || i;
      });
      delete item.checkbox;
      item.images = item.images.split(",").map((i) => {
        return i.trim();
      });
      item.image = item.images[0] || "";
      item.features = JsonToArray(item, "features");
      item.techStack = JsonToArray(item, "techStack");
      return item;
    });
    res.status(200).json({ data: projects, total: count[0].total });
  } catch (error) {
    console.error("Error fetching projects:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/tech-stack", async (req, res) => {
  try {
    const techStack = await db("ba_tech_stack")
      .orderBy("id", "asc")
      .where("status", "=", 1)
      .select();
    // console.log("Tech Stack Data:", techStack);

    if (techStack.length === 0) {
      return res.status(404).json({ error: "Tech stack not found" });
    }
    res.status(200).json(techStack);
  } catch (error) {
    console.error("Error fetching tech stack:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/blogs", async (req, res) => {
  const timeStamp = Date.now();
  const limit = Number(req.query.limit) || 100; // 默认每页100条
  const page = req.query.page || 1; // 默认页码为1
  const keywords = req.query.keywords || "";
  if (!limit || isNaN(limit) || limit <= 0) {
    return res.status(400).json({ error: "Invalid limit parameter" });
  }
  const offset = (page - 1) * limit;
  // 处理keyword的注入

  try {
    let blogs = [];
    if (keywords) {
      blogs = await db("ba_blogdetail")
        .limit(limit)
        .offset(offset)
        .where("title", "like", `%${keywords}%`)
        .orWhere("tags", "like", `%${keywords}%`)
        .orderBy("create_time", "desc")
        .select(
          db.raw("CAST(id AS CHAR) as id"),
          "title",
          "create_time",
          "readTime",
          "tags",
          "image",
          "excerpt"
        );
    } else {
      blogs = await db("ba_blogdetail")
        .limit(limit)
        .offset(offset)
        .orderBy("create_time", "desc")
        .select(
          db.raw("CAST(id AS CHAR) as id"),
          "title",
          "create_time",
          "readTime",
          "tags",
          "image",
          "excerpt"
        );
    }
    // console.log(blogs);

    const count = await db("ba_blogdetail").count("* as total");
    blogs = blogs.map((item) => {
      item.tags = JsonToArray(item, "tags");
      return item;
    });
    res.status(200).json({
      data: blogs,
      total: count[0].total,
      spendTime: Date.now() - timeStamp + " ms",
      code: 200,
      keywords: keywords,
      limit: limit,
      page: page,
    });
  } catch (error) {
    console.error("Error fetching blogs:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/blog/tags", async (req, res) => {
  const timeStamp = Date.now();
  try {
    const tags = await db("ba_blogdetail")
      .select("tags")
      .distinct()
      .whereNotNull("tags");
    if (tags.length === 0) {
      return res.status(404).json({ error: "No tags found" });
    }
    console.log("Fetched blog tags:", tags);

    const formattedTags = tags
      .map((item) => {
        return JsonToArray(item, "tags");
      })
      .flat();
    const uniqueTags = Array.from(new Set(formattedTags));
    res.status(200).json({
      tags: uniqueTags,
      total: uniqueTags.length,
      code: 200,
      spendTime: Date.now() - timeStamp + " ms",
    });
  } catch (error) {
    console.error("Error fetching blog tags:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
router.get("/blog/:id", async (req, res) => {
  const id = req.params.id;
  try {
    const blog = await db("ba_blogdetail").where("id", id).select().first();
    if (!blog) {
      return res.status(404).json({ error: "Blog not found" });
    }
    blog.tags = JsonToArray(blog, "tags");
    
    // 获取当前文章的创建时间
    const currentCreateTime = blog.create_time;
    
    // 获取上一篇文章（创建时间小于当前文章的最新一篇）
    const prevPost = await db("ba_blogdetail")
      .where("create_time", "<", currentCreateTime)
      .orderBy("create_time", "desc")
      .select(db.raw("CAST(id AS CHAR) as id"), "title")
      .first();
    
    // 获取下一篇文章（创建时间大于当前文章的最早一篇）
    const nextPost = await db("ba_blogdetail")
      .where("create_time", ">", currentCreateTime)
      .orderBy("create_time", "asc")
      .select(db.raw("CAST(id AS CHAR) as id"), "title")
      .first();
    
    // 将前后文章信息添加到响应中
    blog.prevPost = prevPost || null;
    blog.nextPost = nextPost || null;
    
    res.status(200).json(blog);
  } catch (error) {
    console.error("Error fetching blog:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});

module.exports = router;
